//
//  IStarTextTools.m
//  zhwp
//
//  Created by flannery on 2019/4/3.
//  Copyright © 2019年 zhxg. All rights reserved.
//

#import "IStarTextTools.h"
#import "IStarColorsTool.h"
#import "IStarConstants.h"

@implementation IStarTextTools

+(BOOL)isTextEmpty:(NSString*)text{
    if (!text || [text isEqualToString:@""]) {
        return YES;
    } else {
        return NO;
    }
}

//判断文字的长度
+ (NSInteger)textLength:(NSString *)text{
    if([IStarTextTools isTextEmpty:text]) {
        return 0;
    } else {
        return text.length;
    }
}

+ (BOOL)isUrl:(NSString *)url{
    NSError *error;
    // 创建NSRegularExpression对象并指定正则表达式
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:@"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+"
                                  options:0
                                  error:&error];
    if (!error) { // 如果没有错误
        // 获取特特定字符串的范围
        NSTextCheckingResult *match = [regex firstMatchInString:url
                                                        options:0
                                                          range:NSMakeRange(0, [url length])];
        if (match) {
            // 截获特定的字符串
            NSString *result = [url substringWithRange:match.range];
            NSLog(@"%@",result);
            return YES;
        }
    } else { // 如果有错误，则把错误打印出来
        NSLog(@"error - %@", error);
        return NO;
    }
    return NO;
}

+ (NSString *)avoidNilString:(NSString *)text{
    if([IStarTextTools isTextEmpty:text]) {
        return @"";
    } else {
        return text;
    }
}

+ (NSString *)avoidNilString:(NSString *)text defaultText:(NSString*)defaultText{
    if([IStarTextTools isTextEmpty:text]) {
        return [IStarTextTools avoidNilString:defaultText];
    } else {
        return text;
    }
}

+(NSString*)avoidNilStringWithId:(id)text {
    if([text isKindOfClass:[NSString class]]) {
        return [IStarTextTools avoidNilString:text];
    } else {
        return @"";
    }
}

//如果长度超过len， 则添加...
+(NSString*)subStringIfGTLen:(NSString*)text len:(NSInteger)len{
    if([IStarTextTools isTextEmpty:text]) {
        return @"";
    }
    if(text.length > len) {
        NSString* lenStr = [text substringToIndex:len];
        return [NSString stringWithFormat:@"%@...", lenStr];
    }
    return text;
}

//分词功能
+(NSArray*)participle:(NSString*)str{
    str = [IStarTextTools avoidNilString:str];
    //NSString *str = @"123\"456\"A\"456\"A\"456\"A\"456\"789\"0";
    //    NSString *str = @"123";
    NSString *splitStr = @"\"";//英文字A符串为分隔符
    NSString *splitStr2 = @" "; //空格分隔字符
    NSString *needReplaceStr = @"\"\"";
    
    // 去掉左右两边空格
    NSString *replaceStr = [str stringByReplacingOccurrencesOfString:needReplaceStr withString:@"A"];
    NSString *trimStr = [self trimString:replaceStr];;//[replaceStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    NSMutableArray *arrayResult = NSMutableArray.new;
    NSRange range;
    while (YES) {
        trimStr = [self trimString:trimStr];
        
        if([self isTextEmpty:trimStr]) {
            break;//没数据了，就不循环了
        }
        NSLog(@"=====>%@", trimStr);
        // 字符串只有1个，就算整个字符串，部分词
        if([IStarTextTools numbersContainOfString:trimStr containsText:splitStr]==1){
            // 用“ ”分隔
            [self addToNsArray:arrayResult source:trimStr];
            trimStr = @"";//不用循环了
            break; //跳出循环
        }
        range = [trimStr rangeOfString:splitStr];
        NSRange rangeTmp = NSMakeRange(0, 0);
        
        if(range.location == NSNotFound) {
            // 用“ ”分隔
            [self addToNsArray:arrayResult source:trimStr];
            trimStr = @"";//不用循环了
            break; //跳出循环
        } else {
            rangeTmp.location = range.location;
            
            //([self numbersContainOfString:trimStr containsText:splitStr]==1);
            
            if(rangeTmp.location > 0) {
                //前边有字符
                [self addToNsArray:arrayResult source:[trimStr substringWithRange:NSMakeRange(0, rangeTmp.location)]];
            }
            
            range = [[trimStr substringFromIndex:rangeTmp.location+1] rangeOfString:splitStr];
            if(range.location == NSNotFound) {
                //后边没有引号了
                rangeTmp.length = trimStr.length - rangeTmp.location;
                [self addToNsArray:arrayResult source:[trimStr substringWithRange:rangeTmp]];
                trimStr = @"";
                break;//跳出循环
            } else {
                rangeTmp.length = range.location;
                NSString *realStr  = [trimStr substringWithRange:NSMakeRange(rangeTmp.location+1, rangeTmp.length)];
                //NSString *realStr = [trimStr substringToIndex:rangeTmp.location];
                if(![self isTextEmpty:realStr]) {
                    [arrayResult addObject:realStr];
                }
                trimStr = [trimStr substringFromIndex:rangeTmp.location+rangeTmp.length+2];
            }
        }
    }
    
    if(![self isTextEmpty:trimStr]) {
        [self addToNsArray:arrayResult source:trimStr];
    }
    
    
    NSMutableArray *arrayNewResult = NSMutableArray.new;
    for (int i=0; i<[arrayResult count]; i++) {
        NSString* myStr = [arrayResult objectAtIndex:i];
        if([myStr containsString:splitStr2]) {
            myStr = [NSString stringWithFormat:@"\"%@\"", myStr];
        }
        [arrayNewResult addObject:myStr];
    }
    
    
//    [arrayNewResult enumerateObjectsUsingBlock:^(NSString  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        NSLog(@"%@", obj);
//    }];
    
    return arrayNewResult;
//    [arrayNewResult enumerateObjectsUsingBlock:^(NSString  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        NSLog(@"%@", obj);
//    }];
}

// 添加到Array中
+(void)addToNsArray:(NSMutableArray*)arrayResult source:(NSString*)str{
    NSArray *array = [str componentsSeparatedByString:@" "];
    for (int i=0; i<[array count]; i++) {
        NSString * oai = [self trimString:[array objectAtIndex:i]];
        if(![IStarTextTools isTextEmpty:oai]) {
            [arrayResult addObject:oai];
        }
    }
}

// 切分字符串
+ (NSArray<NSString*> *)spliteStr:(NSString*)str split:(NSString*)split{
    NSArray * array = [NSArray array];
    if(str) {
        array = [str componentsSeparatedByString:split];
    }
    return array;
}

// 合并字符串
+ (NSString*)combinArray:(NSArray*)arrayStr split:(NSString*)split{
    if(arrayStr) {
        return [arrayStr componentsJoinedByString:split];
    } else {
        return @"";
    }
}

//去掉两边的空格
+(NSString*)trimString:(NSString*)str{
    return [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

//包含字符串的个数
+(NSInteger) numbersContainOfString:(NSString*)text containsText:(NSString*)containsText{
    return [[text mutableCopy] replaceOccurrencesOfString:containsText
                                               withString:@"*"
                                                options:NSLiteralSearch
                                               range:NSMakeRange(0, [text length])];
}

//#pragma mark - 判断字符串是否包含数字
//- (BOOL)isStringContainNumberWith:(NSString *)str {NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];NSInteger count = [numberRegular numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];//count是str中包含[0-9]数字的个数，只要count>0，说明str中包含数字
//    if (count > 0) {return YES;}return NO;}
//
//#pragma mark - 判断字符串是否包含数字
//- (BOOL)isStringContainNumberWith:(NSString *)str {NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];NSInteger count = [numberRegular numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];//count是str中包含[A-Za-z]数字的个数，只要count>0，说明str中包含数字
//    if (count > 0) {return YES;}return NO;}


+ (NSString *)descriptionWithLocaleDictionary:(NSDictionary*)dictionary
{
    NSMutableString *str = [NSMutableString string];
    
    [str appendString:@"{\n"];
    
    // 遍历字典的所有键值对
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [str appendFormat:@"\t%@ = %@,\n", key, obj];
    }];
    
    [str appendString:@"}"];
    
    // 查出最后一个,的范围
    NSRange range = [str rangeOfString:@"," options:NSBackwardsSearch];
    if (range.length != 0) {
        // 删掉最后一个,
        [str deleteCharactersInRange:range];
    }
    
    return str;
}

+ (NSString *)descriptionWithLocaleArray:(NSArray*)array
{
    NSMutableString *str = [NSMutableString string];
    
    [str appendString:@"[\n"];
    
    // 遍历数组的所有元素
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [str appendFormat:@"%@,\n", obj];
    }];
    
    [str appendString:@"]"];
    
    // 查出最后一个,的范围
    NSRange range = [str rangeOfString:@"," options:NSBackwardsSearch];
    if (range.length != 0) {
        // 删掉最后一个,
        [str deleteCharactersInRange:range];
    }
    
    return str;
}

// 得到挂颜色的AttributeString
+(NSMutableAttributedString*)attributeText:(NSString*)text textColor:(UIColor*)textColor font:(UIFont*)font{
    NSString *markAbstract;
    if (textColor) {
        //markAbstract = [NSString stringWithFormat:@"<font color=#999999>%@</font>", text];
        NSString *color = [IStarColorsTool hexStringFromColor:textColor];
        markAbstract = [NSString stringWithFormat:@"<font color=%@>%@</font>",color, text];
    } else {
        markAbstract = [IStarTextTools avoidNilString:text];
    }
    //text = [IStarTextTools avoidNilString:text];
    NSMutableAttributedString *attStrAbs =
        [[NSMutableAttributedString alloc]
         initWithData:[markAbstract dataUsingEncoding:NSUTF8StringEncoding]
         options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
    NSMutableParagraphStyle *paragraphStyleAbs = [[NSMutableParagraphStyle alloc] init];
    paragraphStyleAbs.minimumLineHeight = 63 * WIDTHSCALEISTAR;
    paragraphStyleAbs.maximumLineHeight = 63 * WIDTHSCALEISTAR;
    paragraphStyleAbs.lineBreakMode = NSLineBreakByTruncatingTail;
    [attStrAbs addAttributes:@{NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyleAbs, } range:NSMakeRange(0, attStrAbs.length)];
    
    return attStrAbs;
}

// 获取高度
+ (CGFloat)getWidthWithText:(NSString*)text height:(CGFloat)height font:(CGFloat)font
{
    return [self getWidthWithText:text height:height andFont:[UIFont systemFontOfSize:font]];
}

+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height andFont:(UIFont*)font{
//    // 加上判断，防止传nil等不符合的值，导致程序崩溃
//    if([self isTextEmpty:text]) {
//        text = @"无";
//    }
//    if(!font) {
//        font = [UIFont systemFontOfSize:12];
//    }
//    if(height < 0) {
//        height = 0;
//    }
//    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
//                                     options:NSStringDrawingUsesLineFragmentOrigin
//                                  attributes:@{NSFontAttributeName:font}
//                                     context:nil];
    return [self getRectWithText:text height:height andFont:font].size.width/*rect.size.width*/;
}

+ (CGRect) getRectWithText:(NSString*)text height:(CGFloat)height andFont:(UIFont*)font{
    // 加上判断，防止传nil等不符合的值，导致程序崩溃
    if([self isTextEmpty:text]) {
        text = @"无";
    }
    if(!font) {
        font = [UIFont systemFontOfSize:12];
    }
    if(height < 0) {
        height = 0;
    }
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:font}
                                     context:nil];
    return rect;
}

@end
